package com.zhoug.common.adapters.recycler.layoutmanager;

import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**当item数量超过一定大小时，将RecyclerView高度固定item个数
 * @Author 35574
 * @Date 2020/4/21
 * @Description
 */
public class MaxLinearLayoutManager extends LinearLayoutManager {
    private static final String TAG = ">>>MaxLinearLayout";
    private int maxHeight=3;//最多显示的item个数

    public MaxLinearLayoutManager(Context context) {
        super(context,RecyclerView.VERTICAL,false);
    }

    public MaxLinearLayoutManager(Context context,int maxHeight) {
        super(context,RecyclerView.VERTICAL,false);
        this.maxHeight=maxHeight;
    }

    @Override
    public void onMeasure(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state, int widthSpec, int heightSpec) {
        int itemCount = state.getItemCount();
//        LogUtils.d(TAG, "onMeasure:itemCount="+itemCount);
        if (itemCount > 0) {
            View view = recycler.getViewForPosition(0);
            measureChild(view, widthSpec, heightSpec);
            int itemHeight = view.getMeasuredHeight();
//            LogUtils.d(TAG, "onMeasure:itemHeight="+itemHeight);
            int showHeight = itemHeight * itemCount;
            if(itemCount >= maxHeight){
                showHeight = itemHeight * maxHeight;
            }
            final int width = RecyclerView.LayoutManager.chooseSize(widthSpec,
                    getPaddingLeft() + getPaddingRight(),
                    ViewCompat.getMinimumWidth(view));

            setMeasuredDimension(width, showHeight);
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }

    }

    @Override
    public boolean isAutoMeasureEnabled() {
//            return super.isAutoMeasureEnabled();
        return false;
    }

    public int getMaxHeight() {
        return maxHeight;
    }

    public void setMaxHeight(int maxHeight) {
        this.maxHeight = maxHeight;
    }
}
